import {
  Form,
  Input,
  Link,
  Button,
  Space,
  Typography,
} from '@arco-design/web-react';
import { FormInstance } from '@arco-design/web-react/es/Form';
import React, { useEffect, useRef, useState } from 'react';
import useStorage from '@/utils/useStorage';
import { encrypted } from '@/utils/aes';
import { doLogin } from '@/services/user';
import { IconRightCircle } from '@arco-design/web-react/icon';
import styles from './style/index.module.less';

const { Paragraph } = Typography;

const LoginForm: React.FC = () => {
  const formRef = useRef<FormInstance>();
  const [errorMessage, setErrorMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const [loginParams, setLoginParams] = useStorage('loginParams');

  function afterLoginSuccess(params) {
    // 记住密码
    setLoginParams(JSON.stringify(params));
    // 记录登录状态
    localStorage.setItem('userStatus', 'login');
    // 跳转首页
    window.location.href = '/';
  }

  function login(params) {
    setErrorMessage('');
    setLoading(true);
    doLogin({
      ...params,
      password: encrypted(params.password),
    })
      .then((res) => {
        const { status, message } = res.data;
        if (status === 200) {
          afterLoginSuccess(params);
        } else {
          setErrorMessage(message || '登录出错，请刷新重试');
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }

  function onSubmitClick() {
    formRef.current.validate().then((values) => {
      login(values);
    });
  }

  // 读取 localStorage，设置初始值
  useEffect(() => {
    const hasLogin = !!loginParams;
    if (formRef.current && hasLogin) {
      const parseParams = JSON.parse(loginParams);
      formRef.current.setFieldsValue(parseParams);
    }
  }, [loginParams]);

  return (
    <Typography className={styles['login-form-wrapper']}>
      <Paragraph className={styles['login-form-title']}>账号密码登录</Paragraph>
      <Paragraph className={styles['login-form-sub-title']}>
        没有账号？立即
        <Link
          className={styles['login-form-sub-title-register']}
          hoverable={false}
          href="/register"
        >
          免费注册
          <IconRightCircle className={styles['login-form-sub-title-go']} />
        </Link>
      </Paragraph>
      <Paragraph className={styles['login-form-error-msg']}>
        {errorMessage}
      </Paragraph>
      <Form className={styles['login-form']} layout="vertical" ref={formRef}>
        <Form.Item
          field="mobile"
          rules={[
            { type: 'number', required: true, message: '手机号不能为空' },
          ]}
        >
          <Input
            className={styles['login-form-input']}
            placeholder={'请输入手机号'}
            onPressEnter={onSubmitClick}
            onChange={(value) => {
              formRef.current.setFieldValue(
                'mobile',
                value.replace(/^[^1]+|[^0-9]/g, '').slice(0, 11)
              );
            }}
          />
        </Form.Item>
        <Form.Item
          field="password"
          rules={[
            {
              required: true,
              message: '密码不能为空',
            },
          ]}
        >
          <Input.Password
            className={styles['login-form-input']}
            placeholder={'请输入密码'}
            onPressEnter={onSubmitClick}
          />
        </Form.Item>
        <Space size={16} direction="vertical">
          <Button
            type="primary"
            className={styles['login-form-submit']}
            long
            onClick={onSubmitClick}
            loading={loading}
          >
            登录
          </Button>
        </Space>
        <Space size={16} direction="vertical">
          <Paragraph className={styles['login-form-btn-actions']}>
            <Link
              className={styles['login-form-btn-actions-go']}
              hoverable={false}
              href="/findpwd"
            >
              忘记密码？立即找回
            </Link>
          </Paragraph>
        </Space>
      </Form>
    </Typography>
  );
};

export default LoginForm;
